import router from './router'
import {asyncRoutes,addAsyncRouter } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/','/404','/401'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  const hasSetRouter = store.getters.routes.length!=0
  // 有初始化动态路由&&白名单 直接放行
  if(hasSetRouter && whiteList.includes(to.path)){
    next()
  }else{
     // 1、store.getters.routes为空，还没有添加异步路由
    if(!hasSetRouter){
      const userInfo = await store.dispatch('getUserInfo')
      let roles = userInfo.roles
      const accessRoutes = await store.dispatch('permission/GenerateRoutes', roles)
      addAsyncRouter(accessRoutes)  // 添加动态路由
      next({ ...to, replace: true })
    }else if(!isHasRole(to)){  // 2、添加异步路由了，路由中没有to
      console.log('没有 to 的权限')
      // 判断to.path在asyncRoutes中有没有，没有则404，有则401
      if(is404(to)){  // 3、添加异步路由了，路由中没有to，异步路由表asyncRoutes中也没有to
        next({ path:'/404' }) 
      }else{  // 4、添加异步路由了，路由中没有to，异步路由表asyncRoutes中有to
        next({ path:'/401' }) 
      }
    }else{  // 5、添加异步路由了，路由中有to，放行，
      next()
    }
  }
  NProgress.done()
  })
 


/**
 * 判断是否有权限跳转到to
 * router.getRoutes()中是否to.path
 */
function isHasRole(toRoute){
  let routes = router.getRoutes()
  for (const item of routes) {
    // console.log(item.path,toRoute.path,item.path == toRoute.path)
    if(item.path == toRoute.path){
      return true
    }
  }
  return false
}
/**
 * 判断是否404
 * rasyncRoutes中是否to.path
 */
function is404(toRoute){
  let routes = asyncRoutes
  for (const item of routes) {
    // console.log(item.path,toRoute.path,item.path == toRoute.path)
    if(item.path == toRoute.path){
      return false
    }
  }
  return true
}